package com.meowcook.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.meowcook.common.AppResult;
import com.meowcook.common.ResultCode;
import com.meowcook.dao.MembersMapper;
import com.meowcook.dao.MessageMapper;
import com.meowcook.dao.SessionMapper;
import com.meowcook.exception.AppException;
import com.meowcook.mapper.MessagePojoMapper;
import com.meowcook.pojo.dto.MessageDTO;
import com.meowcook.pojo.po.Message;
import com.meowcook.pojo.po.Session;
import com.meowcook.pojo.vo.MessageVO;
import com.meowcook.service.IMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 28792
 * Date: 2025-11-15
 * Time: 14:17
 */
@Slf4j
@Service
public class MessageServiceImpl implements IMessageService {

    @Resource
    private MessagePojoMapper messagePojoMapper;
    @Resource
    private MessageMapper messageMapper;
    @Resource
    private MembersMapper membersMapper;
    @Resource
    private SessionMapper sessionMapper;
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public MessageVO createMessage(MessageDTO messageDTO) {
        // 创建消息
        Message message = messagePojoMapper.toPO(messageDTO);
        message.setIsDeleted((byte) 0);
        message.setCreateTime(new Date());
        message.setUpdateTime(message.getCreateTime());
        int row = messageMapper.insert(message);
        if (row != 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));

        // 在Members表中更新InfoRecord
        row = membersMapper.updateInfoRecordBySessionId(message.getSessionId(), message.getId());
        if (row < 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));

        // 更新会话时间
        Session session = new Session();
        session.setId(message.getSessionId());
        session.setUpdateTime(message.getCreateTime());
        row = sessionMapper.updateByPrimaryKeySelective(session);
        if (row != 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));

        return messagePojoMapper.toVO(message);
    }

    @Override
    public Integer getUncheckNum(Long userId) {
        Integer num = messageMapper.selectUncheckNumByUserId(userId);
        return num == null ? (Integer) 0 : num;
    }

    @Override
    public ArrayList<Long> getMessageIdList(Long userId, Long sessionId){
        // 获取InfoRecord
        String infoRecord = membersMapper.selectInfoRecord(userId, sessionId);
        // 如果InfoRecord为空，则返回空数组
        if (infoRecord == null) return new ArrayList<>();
        try {
            ArrayList<Long> idList = objectMapper.readValue(infoRecord,
                    objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, Long.class));
            return idList;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ArrayList<MessageVO> getMessageList(ArrayList<Long> messageIdList) {
        if (messageIdList.isEmpty()) return new ArrayList<>();
        ArrayList<Message> messages = messageMapper.selectByIdList(messageIdList);
        return messagePojoMapper.toVO(messages);
    }

    @Override
    public void updateUncheckNum(Long id, Long sessionId, Integer i) {
        int row = membersMapper.updateUncheckNum(id, sessionId, i);
        if (row != 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
    }

    @Override
    public void deleteMessage(Long userId, Long sessionId, ArrayList<Long> messageIdList) {
        try {
            String newRecord = objectMapper.writeValueAsString(messageIdList);
            int row = membersMapper.changeInfoRecordBySessionId(userId, sessionId, newRecord);
            if (row != 1) throw new AppException(AppResult.fail(ResultCode.ERROR_SERVICE));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
